

<!DOCTYPE html>
<html lang="zh-CN" data-default-color-scheme=auto>



<head>
  <meta charset="UTF-8">
  <link rel="apple-touch-icon" sizes="76x76" href="/img/fluid.png">
  <link rel="icon" href="/img/fluid.png">
  <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=5.0, shrink-to-fit=no">
  <meta http-equiv="x-ua-compatible" content="ie=edge">
  
  <meta name="theme-color" content="#2f4154">
  <meta name="author" content="深海火锅店">
  <meta name="keywords" content="">
  
    <meta name="description" content="为什么要分组？数据分组是按照逻辑次序把具有重复值的字段进行合并。比如说，一个数据库存储了关于所有员工的信息，有些员工住在不同的城市里，有些员工住在同一个城市里。我们可能需要进行一个查询，了解每个指定城市里的员工的信息。这时就是在根据城市对员工进行分组，并且创建一个统计报告。 假设我们想了解每个城市的员工的平均薪水，这时可以对SALARY字段使用AVG函数，并且使用GROUP BY子句把结果按照城市">
<meta property="og:type" content="article">
<meta property="og:title" content="DB11_数据库分组与排序">
<meta property="og:url" content="http://example.com/2022/12/23/%E6%95%B0%E6%8D%AE%E5%BA%93/MySQL/%E5%A4%A7%E6%95%B0%E6%8D%AE%E5%AD%A6%E4%B9%A0/DB10&DB11/DB11_%E6%95%B0%E6%8D%AE%E5%BA%93%E5%88%86%E7%BB%84%E4%B8%8E%E6%8E%92%E5%BA%8F/index.html">
<meta property="og:site_name" content="Hexo">
<meta property="og:description" content="为什么要分组？数据分组是按照逻辑次序把具有重复值的字段进行合并。比如说，一个数据库存储了关于所有员工的信息，有些员工住在不同的城市里，有些员工住在同一个城市里。我们可能需要进行一个查询，了解每个指定城市里的员工的信息。这时就是在根据城市对员工进行分组，并且创建一个统计报告。 假设我们想了解每个城市的员工的平均薪水，这时可以对SALARY字段使用AVG函数，并且使用GROUP BY子句把结果按照城市">
<meta property="og:locale" content="zh_CN">
<meta property="og:image" content="https://gitee.com/tongstyle/blog-img/raw/master/img/202301201953353.png">
<meta property="og:image" content="https://gitee.com/tongstyle/blog-img/raw/master/img/202301201953244.png">
<meta property="og:image" content="https://gitee.com/tongstyle/blog-img/raw/master/img/202301201953468.png">
<meta property="og:image" content="https://gitee.com/tongstyle/blog-img/raw/master/img/202301201953410.png">
<meta property="article:published_time" content="2022-12-23T02:30:00.000Z">
<meta property="article:modified_time" content="2024-02-15T16:04:49.014Z">
<meta property="article:author" content="深海火锅店">
<meta property="article:tag" content="大数据">
<meta name="twitter:card" content="summary_large_image">
<meta name="twitter:image" content="https://gitee.com/tongstyle/blog-img/raw/master/img/202301201953353.png">
  
  
    <meta name="referrer" content="no-referrer-when-downgrade">
  
  
  <title>DB11_数据库分组与排序 - Hexo</title>

  <link  rel="stylesheet" href="https://lib.baomitu.com/twitter-bootstrap/4.6.1/css/bootstrap.min.css" />



  <link  rel="stylesheet" href="https://lib.baomitu.com/github-markdown-css/4.0.0/github-markdown.min.css" />

  <link  rel="stylesheet" href="https://lib.baomitu.com/hint.css/2.7.0/hint.min.css" />

  <link  rel="stylesheet" href="https://lib.baomitu.com/fancybox/3.5.7/jquery.fancybox.min.css" />



<!-- 主题依赖的图标库，不要自行修改 -->
<!-- Do not modify the link that theme dependent icons -->

<link rel="stylesheet" href="//at.alicdn.com/t/font_1749284_hj8rtnfg7um.css">



<link rel="stylesheet" href="//at.alicdn.com/t/font_1736178_lbnruvf0jn.css">


<link  rel="stylesheet" href="/css/main.css" />


  <link id="highlight-css" rel="stylesheet" href="/css/highlight.css" />
  
    <link id="highlight-css-dark" rel="stylesheet" href="/css/highlight-dark.css" />
  




  <script id="fluid-configs">
    var Fluid = window.Fluid || {};
    Fluid.ctx = Object.assign({}, Fluid.ctx)
    var CONFIG = {"hostname":"example.com","root":"/","version":"1.9.3","typing":{"enable":true,"typeSpeed":70,"cursorChar":"_","loop":false,"scope":[]},"anchorjs":{"enable":true,"element":"h1,h2,h3,h4,h5,h6","placement":"left","visible":"hover","icon":""},"progressbar":{"enable":true,"height_px":3,"color":"#29d","options":{"showSpinner":false,"trickleSpeed":100}},"code_language":{"enable":true,"default":"TEXT"},"copy_btn":true,"image_caption":{"enable":true},"image_zoom":{"enable":true,"img_url_replace":["",""]},"toc":{"enable":true,"placement":"right","headingSelector":"h1,h2,h3,h4,h5,h6","collapseDepth":0},"lazyload":{"enable":true,"loading_img":"/img/loading.gif","onlypost":false,"offset_factor":2},"web_analytics":{"enable":false,"follow_dnt":true,"baidu":null,"google":null,"gtag":null,"tencent":{"sid":null,"cid":null},"woyaola":null,"cnzz":null,"leancloud":{"app_id":null,"app_key":null,"server_url":null,"path":"window.location.pathname","ignore_local":false}},"search_path":"/local-search.xml"};

    if (CONFIG.web_analytics.follow_dnt) {
      var dntVal = navigator.doNotTrack || window.doNotTrack || navigator.msDoNotTrack;
      Fluid.ctx.dnt = dntVal && (dntVal.startsWith('1') || dntVal.startsWith('yes') || dntVal.startsWith('on'));
    }
  </script>
  <script  src="/js/utils.js" ></script>
  <script  src="/js/color-schema.js" ></script>
  


  
<meta name="generator" content="Hexo 6.3.0"></head>


<body>
  

  <header>
    

<div class="header-inner" style="height: 70vh;">
  <nav id="navbar" class="navbar fixed-top  navbar-expand-lg navbar-dark scrolling-navbar">
  <div class="container">
    <a class="navbar-brand" href="/">
      <strong>Fluid</strong>
    </a>

    <button id="navbar-toggler-btn" class="navbar-toggler" type="button" data-toggle="collapse"
            data-target="#navbarSupportedContent"
            aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
      <div class="animated-icon"><span></span><span></span><span></span></div>
    </button>

    <!-- Collapsible content -->
    <div class="collapse navbar-collapse" id="navbarSupportedContent">
      <ul class="navbar-nav ml-auto text-center">
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/">
                <i class="iconfont icon-home-fill"></i>
                首页
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/archives/">
                <i class="iconfont icon-archive-fill"></i>
                归档
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/categories/">
                <i class="iconfont icon-category-fill"></i>
                分类
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/tags/">
                <i class="iconfont icon-tags-fill"></i>
                标签
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/about/">
                <i class="iconfont icon-user-fill"></i>
                关于
              </a>
            </li>
          
        
        
          <li class="nav-item" id="search-btn">
            <a class="nav-link" target="_self" href="javascript:;" data-toggle="modal" data-target="#modalSearch" aria-label="Search">
              &nbsp;<i class="iconfont icon-search"></i>&nbsp;
            </a>
          </li>
          
        
        
          <li class="nav-item" id="color-toggle-btn">
            <a class="nav-link" target="_self" href="javascript:;" aria-label="Color Toggle">&nbsp;<i
                class="iconfont icon-dark" id="color-toggle-icon"></i>&nbsp;</a>
          </li>
        
      </ul>
    </div>
  </div>
</nav>

  

<div id="banner" class="banner" parallax=true
     style="background: url('/img/background.jpg') no-repeat center center; background-size: cover;">
  <div class="full-bg-img">
    <div class="mask flex-center" style="background-color: rgba(0, 0, 0, 0.3)">
      <div class="banner-text text-center fade-in-up">
        <div class="h2">
          
            <span id="subtitle" data-typed-text="DB11_数据库分组与排序"></span>
          
        </div>

        
          
  <div class="mt-3">
    
    
      <span class="post-meta">
        <i class="iconfont icon-date-fill" aria-hidden="true"></i>
        <time datetime="2022-12-23 10:30" pubdate>
          2022年12月23日 上午
        </time>
      </span>
    
  </div>

  <div class="mt-1">
    
      <span class="post-meta mr-2">
        <i class="iconfont icon-chart"></i>
        
          4k 字
        
      </span>
    

    
      <span class="post-meta mr-2">
        <i class="iconfont icon-clock-fill"></i>
        
        
        
          34 分钟
        
      </span>
    

    
    
  </div>


        
      </div>

      
    </div>
  </div>
</div>

</div>

  </header>

  <main>
    
      

<div class="container-fluid nopadding-x">
  <div class="row nomargin-x">
    <div class="side-col d-none d-lg-block col-lg-2">
      

    </div>

    <div class="col-lg-8 nopadding-x-md">
      <div class="container nopadding-x-md" id="board-ctn">
        <div id="board">
          <article class="post-content mx-auto">
            <!-- SEO header -->
            <h1 style="display: none">DB11_数据库分组与排序</h1>
            
            
              <div class="markdown-body">
                
                <h4 id="为什么要分组？"><a href="#为什么要分组？" class="headerlink" title="为什么要分组？"></a>为什么要分组？</h4><p>数据分组是按照逻辑次序把具有重复值的字段进行合并。比如说，一个数据库存储了关于所有员工的信息，有些员工住在不同的城市里，有些员工住在同一个城市里。我们可能需要进行一个查询，了解每个指定城市里的员工的信息。这时就是在根据城市对员工进行分组，并且创建一个统计报告。</p>
<p>假设我们想了解每个城市的员工的平均薪水，这时可以对SALARY字段使用AVG函数，并且使用GROUP BY子句把结果按照城市进行分组。</p>
<p>数据分组是通过在SELECT语句(查询)里使用GROUP BY子句来实现的。基于前面汇总函数，这一章将讨论如何组合使用汇总函数与GROUP BY子句，从而更高效地显示查询结果。</p>
<h4 id="GROUP-BY子句"><a href="#GROUP-BY子句" class="headerlink" title="GROUP BY子句"></a>GROUP BY子句</h4><p>GROUP BY子句与SELECT语句配合使用，把相同的数据划分为一组。在SELECT语句里，GROUP BY子句在WHERE子句之后,在ORDER BY子句之前。</p>
<p>GROUP BY子句在查询中的位置如下所示:</p>
<figure class="highlight sql"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><code class="hljs sql"><span class="hljs-keyword">SELECT</span> column1, column2,<br><span class="hljs-keyword">FROM</span> table1, table2<br><span class="hljs-keyword">GROUP</span> <span class="hljs-keyword">BY</span> column1, column2<br><span class="hljs-keyword">ORDER</span> <span class="hljs-keyword">BY</span> column1, column2;<br></code></pre></td></tr></table></figure>

<p>在使用GROUP BY子句的时候，要养成按顺序书写的习惯，以确保逻辑正确。GROUP BY子句对CPU的运行效率有很大影响，如果我们不对提供给它的数据进行过滤，那么后期很可能需要删除大量的无用数据。所以，需要使用WHERE子句来缩小数据范围，从而确保对有用的数据进行分组。<br>在SQL中也可以加入ORDER BY子句并且使用GROUP BY子句中的列序对返回结果进行排序，后续内容将对此进行深入介绍。</p>
<h4 id="GROUP-BY规则"><a href="#GROUP-BY规则" class="headerlink" title="GROUP BY规则"></a>GROUP BY规则</h4><p><strong>出现在SELECT子句中的单独的列,<code>应该</code>出现在GROUP BY子句中作为分组列</strong><br>在GROUP BY子句里可以使用字段名称，也可以使用一个整数来代表字段。另外，分组字段的顺序不一定需要与SELECT子句中的字段顺序相同</p>
<p><strong>分组列可以不出现在SELECT子句中，该情况最好避免出现</strong><br>如果字段在SELECT语句里找不到，但是又出现在GROUP BY子句，虽然无法不报错，但是不太合乎逻辑的:如果数据根本就不显示，我们如何对其进行分组，意义何在呢?</p>
<p><strong>分组列可出现在SELECT子句中的一个复合表达式中</strong></p>
<p><strong>如果GROUP BY后面是一个复合表达式，那么在SELECT子句中，它必须整体作为一个表达式的一部分才能使用。</strong></p>
<figure class="highlight sql"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><code class="hljs sql"><span class="hljs-keyword">select</span> date_format(ord_date, <span class="hljs-string">&#x27;%Y-%m-%d&#x27;</span>) <span class="hljs-keyword">as</span> <span class="hljs-string">&#x27;时间&#x27;</span>,<span class="hljs-built_in">sum</span>(ord_num)<br><span class="hljs-keyword">from</span> orders_tbl<br><span class="hljs-keyword">group</span> <span class="hljs-keyword">by</span> date_format(ord_date, <span class="hljs-string">&#x27;%Y-%m-%d&#x27;</span>);<br></code></pre></td></tr></table></figure>

<h4 id="创建分组和使用聚合函数"><a href="#创建分组和使用聚合函数" class="headerlink" title="创建分组和使用聚合函数"></a>创建分组和使用聚合函数</h4><p>SELECT语句在使用GROUP BY子句时必须满足一定条件。特别是SELECT子句的字段应该出现在GROUPBY子句里，除了聚合函数参数中使用的字段。GROUP BY子句里的字段不必与SELECT子句里的字段具有相同的顺序。只要SELECT子句的字段名称是符合条件的，它的名称就应该出现在GROUP BY子句里。</p>
<ol>
<li>select匹配group by字段列表</li>
<li>顺序不要求</li>
</ol>
<p>对于MySQL，与Oracle和其他的数据库，不太遵循标准SQL。常规的SQL要求GROUP BY来说一定要结合聚合函数，而且选择的字段除了聚合函数外，还必须在GROUP BY中出现，否则报错;但是在MySQL中不会报错，其操作相当于先进行GROUP BY,然后在每个GROUP BY下面进行LIMIT 1。</p>
<h4 id="GROUP-BY例子"><a href="#GROUP-BY例子" class="headerlink" title="GROUP BY例子"></a>GROUP BY例子</h4><figure class="highlight sql"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><code class="hljs sql"><span class="hljs-keyword">select</span> emp_id, position, date_hire, pay_rate, date_last_raise, salary, bonus<br><span class="hljs-keyword">from</span> employee_pay_tbl<br><span class="hljs-keyword">group</span> <span class="hljs-keyword">by</span> emp_id, salary;<br><br><span class="hljs-keyword">select</span> city, <span class="hljs-built_in">avg</span>(pay_rate) <span class="hljs-string">&#x27;时薪平均值&#x27;</span>, <span class="hljs-built_in">avg</span>(salary) <span class="hljs-string">&#x27;月薪平均值&#x27;</span><br><span class="hljs-keyword">from</span> emp_pay_tmp<br><span class="hljs-keyword">where</span> city <span class="hljs-keyword">in</span> (<span class="hljs-string">&#x27;WHITELAND&#x27;</span>, <span class="hljs-string">&#x27;INDIANAPOLIS&#x27;</span>)<br><span class="hljs-keyword">group</span> <span class="hljs-keyword">by</span> city<br><span class="hljs-keyword">order</span> <span class="hljs-keyword">by</span> <span class="hljs-number">2</span>, <span class="hljs-number">3</span>;<br># 以数字代替字段名称，比如排序 <span class="hljs-keyword">order</span> <span class="hljs-keyword">by</span> <span class="hljs-number">2</span>,<span class="hljs-number">3</span><br># 同等与 <span class="hljs-keyword">order</span> <span class="hljs-keyword">by</span> <span class="hljs-built_in">avg</span>(pay_rate) <span class="hljs-string">&#x27;时薪平均值&#x27;</span>, <span class="hljs-built_in">avg</span>(salary) <span class="hljs-string">&#x27;月薪平均值&#x27;</span> ，即以第二个和第三个字段排序<br></code></pre></td></tr></table></figure>

<h4 id="ROLLUP语句"><a href="#ROLLUP语句" class="headerlink" title="ROLLUP语句"></a>ROLLUP语句</h4><p>在某些情况下，对分组数据进行小计是很有用的。比如，用户既要分析各种产品每年分别在不同国家的销售数据，也需要看到每年在每个国家所有产品的销售数据总额。ANSI SQL提供了<code>CUBE和ROLLUP</code>语句来解决这类问题。<br>各种数据具体的实现不一样，MySQL提供了WITH ROLLUP修饰符，该修饰符可以对分组后各组的某个列的结果值进行汇总，并在结果中输出，即提供更高一级的聚合操作。因此，ROLLUP使您能够使用单个查询在多个分析级别回答问题。例如，ROLLUP可用于为OLAP(在线分析处理)操作提供支持。<br>ROLLUP语句可以用来进行小计，即在全部分组数据的基础上，对其中的一部分进行汇总。其ANSI语法结构如下:<br>GROUP BY ROLLUP (column list of grouping sets)<br>ROLLUP语句执行过程:在完成了基本的分组数据汇总以后，按照从右向左的顺序，每次去掉字段列表中的最后一个字段，再对剩余的字段进行分组统计，并将获得的小计结果插入返回表中，被去掉的字段位置使用NULL填充，最后，再对全表进行一次统计，所有字段位置均使用NULL填充。<br>MySQL的ROLLUP语法结构稍有不同</p>
<figure class="highlight sql"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><code class="hljs sql"><span class="hljs-keyword">GROUP</span> <span class="hljs-keyword">BY</span> <span class="hljs-keyword">column</span> list <span class="hljs-keyword">of</span> <span class="hljs-keyword">grouping</span> sets <span class="hljs-keyword">WITH</span> <span class="hljs-keyword">ROLLUP</span><br></code></pre></td></tr></table></figure>

<p>示例：</p>
<figure class="highlight sql"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><code class="hljs sql"><span class="hljs-keyword">select</span> date_format(month_ending, <span class="hljs-string">&#x27;%Y&#x27;</span>), car_category, <span class="hljs-built_in">sum</span>(quantity)<br><span class="hljs-keyword">from</span> car_sold<br><span class="hljs-keyword">where</span> month_ending<span class="hljs-operator">&gt;=</span><span class="hljs-string">&#x27;2001-01-01&#x27;</span><br><span class="hljs-keyword">group</span> <span class="hljs-keyword">by</span> <span class="hljs-number">1</span>,<span class="hljs-number">2</span>;<br></code></pre></td></tr></table></figure>

<figure class="highlight sql"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><code class="hljs sql"><span class="hljs-keyword">select</span> date_format(month_ending, <span class="hljs-string">&#x27;%Y&#x27;</span>), car_category, <span class="hljs-built_in">sum</span>(quantity)<br><span class="hljs-keyword">from</span> car_sold<br><span class="hljs-keyword">where</span> month_ending<span class="hljs-operator">&gt;=</span><span class="hljs-string">&#x27;2001-01-01&#x27;</span><br><span class="hljs-keyword">group</span> <span class="hljs-keyword">by</span> <span class="hljs-number">1</span>,<span class="hljs-number">2</span> <span class="hljs-keyword">with</span> <span class="hljs-keyword">rollup</span> ;<br></code></pre></td></tr></table></figure>

<p>在完成了基本的分组数据汇总以后，去掉了最后一个字段(车型)，并根据剩余的字段(年份)，再次进行分组统计，并将结果插入返回表。最后，还对全表进行了一次统计。</p>
<p><img src="https://gitee.com/tongstyle/blog-img/raw/master/img/202301201953353.png" srcset="/img/loading.gif" lazyload alt="1"></p>
<p><img src="https://gitee.com/tongstyle/blog-img/raw/master/img/202301201953244.png" srcset="/img/loading.gif" lazyload alt="2"></p>
<h5 id="rollup练习"><a href="#rollup练习" class="headerlink" title="rollup练习"></a>rollup练习</h5><p>rollup() 是分组函数的一种用法，配合 group by 使用。</p>
<p>rollup() 能够起到一个多次分组求值的效果。</p>
<figure class="highlight sql"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><code class="hljs sql"><span class="hljs-keyword">select</span><br>	<span class="hljs-built_in">sum</span>(字段A)<br><span class="hljs-keyword">from</span><br>	表名<br><span class="hljs-keyword">group</span> <span class="hljs-keyword">by</span><br>	<span class="hljs-keyword">rollup</span>(字段A) <br></code></pre></td></tr></table></figure>
<p>作用：<br>一共执行了两次分组求和：<br>第1步：以“字段A”作为条件，进行分组求和；<br>第2步：以所有记录作为一个大组，进行求和；</p>
<p><img src="https://gitee.com/tongstyle/blog-img/raw/master/img/202301201953468.png" srcset="/img/loading.gif" lazyload alt="3"></p>
<p><img src="https://gitee.com/tongstyle/blog-img/raw/master/img/202301201953410.png" srcset="/img/loading.gif" lazyload alt="4"></p>
<h6 id="多个字段分组的语法："><a href="#多个字段分组的语法：" class="headerlink" title="多个字段分组的语法："></a>多个字段分组的语法：</h6><figure class="highlight sql"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><code class="hljs sql"><span class="hljs-keyword">select</span><br>	<span class="hljs-built_in">sum</span>(字段A), <br>	<span class="hljs-built_in">sum</span>(字段B)<br><span class="hljs-keyword">from</span><br>	表名<br><span class="hljs-keyword">group</span> <span class="hljs-keyword">by</span><br>	<span class="hljs-keyword">rollup</span>(字段A, 字段B) <br></code></pre></td></tr></table></figure>
<p>作用：<br>一共执行了三次分组求和：<br>第1步：以“字段A”和“字段B”联合起来作为条件，进行分组求和；<br>第2步：以“字段A”作为条件，进行分组求和；<br>第3步：以所有记录作为一个大组，进行求和；</p>
<h4 id="CUBE语句"><a href="#CUBE语句" class="headerlink" title="CUBE语句"></a>CUBE语句</h4><p>CUBE语句的工作方式与ROLLLP有所不同。它对分组列表中的所有字段进行排列组合，并根据每一种组合结果，分别进行统计汇总。最后，CUBE语句也会对全表进行统计，体现立(N)方体的概念<br>CUBE的ANSI语法结构如下:<br>GROUP BY CUBE ( column list of grouping sets)<br>CUBE语句通常被用来生成交叉报表〉比如需要根据月份(month code)、省份(province)、商品类别(prod_cartegory)三个字段获得销售数据的分组统计结果，GROUP BY语句会根据一下的每一种字段组合分组汇总，并产生结果。</p>
<ul>
<li>month_code</li>
<li>month_code, privince</li>
<li>month_code, prod_category</li>
<li>month_code, province, prod_categoryprovince</li>
<li>province, prod_categoryprod_category</li>
<li>grand_total</li>
</ul>
<blockquote>
<p>MySQL目前还不支持CUBE操作!!!</p>
</blockquote>
<h4 id="HAVING子句"><a href="#HAVING子句" class="headerlink" title="HAVING子句"></a>HAVING子句</h4><p>HAVING子句在SELECT语句里与GROUP BY子句联合使用时，用于告诉GROUP BY子句在输出里包含哪些分组。HAVING对于GROUP BY的作用相当于WHERE对于SELECT的作用。换句话说，WHERE子句设定被选择字段的条件，而HAVING子句设置GROUP BY子句形成分组的条件。因此，使用HAVING子句可以让结果里包含或是去除整组的数据。</p>
<ul>
<li>IO上的过滤(WHERE)</li>
<li>内存中的过滤(HAVING)<br>下面是HAVING子句在查询里的位置:<figure class="highlight sql"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><code class="hljs sql"><span class="hljs-keyword">SELECT</span> column_name1, column_name2FROM table_name1, table_name2WHERE conditions<br><span class="hljs-keyword">GROUP</span> <span class="hljs-keyword">BY</span> column_name1, column_name2<br><span class="hljs-keyword">HAVING</span> conditions<br><span class="hljs-keyword">ORDER</span> <span class="hljs-keyword">BY</span> column_name1, column_name2<br></code></pre></td></tr></table></figure>
HAVING子句必须跟在GROUP BY子句之后,在ORDER BY子句之前。<br>聚合函数无法结合where使用<br>如：where avg(salary)&gt;300<br>正确写法: having avg(salary)&gt;300</li>
</ul>

                
              </div>
            
            <hr/>
            <div>
              <div class="post-metas my-3">
  
    <div class="post-meta mr-3 d-flex align-items-center">
      <i class="iconfont icon-category"></i>
      

<span class="category-chains">
  
  
    
      <span class="category-chain">
        
  <a href="/categories/%E5%A4%A7%E6%95%B0%E6%8D%AE/" class="category-chain-item">大数据</a>
  
  

      </span>
    
  
</span>

    </div>
  
  
    <div class="post-meta">
      <i class="iconfont icon-tags"></i>
      
        <a href="/tags/%E5%A4%A7%E6%95%B0%E6%8D%AE/">#大数据</a>
      
    </div>
  
</div>


              
  

  <div class="license-box my-3">
    <div class="license-title">
      <div>DB11_数据库分组与排序</div>
      <div>http://example.com/2022/12/23/数据库/MySQL/大数据学习/DB10&amp;DB11/DB11_数据库分组与排序/</div>
    </div>
    <div class="license-meta">
      
        <div class="license-meta-item">
          <div>作者</div>
          <div>深海火锅店</div>
        </div>
      
      
        <div class="license-meta-item license-meta-date">
          <div>发布于</div>
          <div>2022年12月23日</div>
        </div>
      
      
      
        <div class="license-meta-item">
          <div>许可协议</div>
          <div>
            
              
              
                <a target="_blank" href="https://creativecommons.org/licenses/by/4.0/">
                  <span class="hint--top hint--rounded" aria-label="BY - 署名">
                    <i class="iconfont icon-by"></i>
                  </span>
                </a>
              
            
          </div>
        </div>
      
    </div>
    <div class="license-icon iconfont"></div>
  </div>



              
                <div class="post-prevnext my-3">
                  <article class="post-prev col-6">
                    
                    
                      <a href="/2022/12/23/%E7%BC%96%E7%A8%8B%E8%AF%AD%E8%A8%80/Java/%E5%AD%A6%E4%B9%A0/%E6%A1%86%E6%9E%B6/SpringCloud/day1/%E5%88%9D%E8%AF%86springcloud/%E5%88%9D%E8%AF%86springcloud/" title="初识springcloud">
                        <i class="iconfont icon-arrowleft"></i>
                        <span class="hidden-mobile">初识springcloud</span>
                        <span class="visible-mobile">上一篇</span>
                      </a>
                    
                  </article>
                  <article class="post-next col-6">
                    
                    
                      <a href="/2022/12/23/%E6%95%B0%E6%8D%AE%E5%BA%93/MySQL/%E5%A4%A7%E6%95%B0%E6%8D%AE%E5%AD%A6%E4%B9%A0/DB10&amp;DB11/DB10_%E6%95%B0%E6%8D%AE%E5%BA%93%E8%81%9A%E5%90%88%E5%87%BD%E6%95%B0/" title="DB10_数据库聚合函数">
                        <span class="hidden-mobile">DB10_数据库聚合函数</span>
                        <span class="visible-mobile">下一篇</span>
                        <i class="iconfont icon-arrowright"></i>
                      </a>
                    
                  </article>
                </div>
              
            </div>

            
          </article>
        </div>
      </div>
    </div>

    <div class="side-col d-none d-lg-block col-lg-2">
      
  <aside class="sidebar" style="margin-left: -1rem">
    <div id="toc">
  <p class="toc-header"><i class="iconfont icon-list"></i>&nbsp;目录</p>
  <div class="toc-body" id="toc-body"></div>
</div>



  </aside>


    </div>
  </div>
</div>





  



  



  



  



  







    

    
      <a id="scroll-top-button" aria-label="TOP" href="#" role="button">
        <i class="iconfont icon-arrowup" aria-hidden="true"></i>
      </a>
    

    
      <div class="modal fade" id="modalSearch" tabindex="-1" role="dialog" aria-labelledby="ModalLabel"
     aria-hidden="true">
  <div class="modal-dialog modal-dialog-scrollable modal-lg" role="document">
    <div class="modal-content">
      <div class="modal-header text-center">
        <h4 class="modal-title w-100 font-weight-bold">搜索</h4>
        <button type="button" id="local-search-close" class="close" data-dismiss="modal" aria-label="Close">
          <span aria-hidden="true">&times;</span>
        </button>
      </div>
      <div class="modal-body mx-3">
        <div class="md-form mb-5">
          <input type="text" id="local-search-input" class="form-control validate">
          <label data-error="x" data-success="v" for="local-search-input">关键词</label>
        </div>
        <div class="list-group" id="local-search-result"></div>
      </div>
    </div>
  </div>
</div>

    

    
  </main>

  <footer>
    <div class="footer-inner">
  
    <div class="footer-content">
       <a href="https://hexo.io" target="_blank" rel="nofollow noopener"><span>Hexo</span></a> <i class="iconfont icon-love"></i> <a href="https://github.com/fluid-dev/hexo-theme-fluid" target="_blank" rel="nofollow noopener"><span>Fluid</span></a> 
    </div>
  
  
    <div class="statistics">
  
  

  
    
      <span id="busuanzi_container_site_pv" style="display: none">
        总访问量 
        <span id="busuanzi_value_site_pv"></span>
         次
      </span>
    
    
      <span id="busuanzi_container_site_uv" style="display: none">
        总访客数 
        <span id="busuanzi_value_site_uv"></span>
         人
      </span>
    
    
  
</div>

  
  
  
</div>

  </footer>

  <!-- Scripts -->
  
  <script  src="https://lib.baomitu.com/nprogress/0.2.0/nprogress.min.js" ></script>
  <link  rel="stylesheet" href="https://lib.baomitu.com/nprogress/0.2.0/nprogress.min.css" />

  <script>
    NProgress.configure({"showSpinner":false,"trickleSpeed":100})
    NProgress.start()
    window.addEventListener('load', function() {
      NProgress.done();
    })
  </script>


<script  src="https://lib.baomitu.com/jquery/3.6.0/jquery.min.js" ></script>
<script  src="https://lib.baomitu.com/twitter-bootstrap/4.6.1/js/bootstrap.min.js" ></script>
<script  src="/js/events.js" ></script>
<script  src="/js/plugins.js" ></script>


  <script  src="https://lib.baomitu.com/typed.js/2.0.12/typed.min.js" ></script>
  <script>
    (function (window, document) {
      var typing = Fluid.plugins.typing;
      var subtitle = document.getElementById('subtitle');
      if (!subtitle || !typing) {
        return;
      }
      var text = subtitle.getAttribute('data-typed-text');
      
        typing(text);
      
    })(window, document);
  </script>




  
    <script  src="/js/img-lazyload.js" ></script>
  




  
<script>
  Fluid.utils.createScript('https://lib.baomitu.com/tocbot/4.18.2/tocbot.min.js', function() {
    var toc = jQuery('#toc');
    if (toc.length === 0 || !window.tocbot) { return; }
    var boardCtn = jQuery('#board-ctn');
    var boardTop = boardCtn.offset().top;

    window.tocbot.init(Object.assign({
      tocSelector     : '#toc-body',
      contentSelector : '.markdown-body',
      linkClass       : 'tocbot-link',
      activeLinkClass : 'tocbot-active-link',
      listClass       : 'tocbot-list',
      isCollapsedClass: 'tocbot-is-collapsed',
      collapsibleClass: 'tocbot-is-collapsible',
      scrollSmooth    : true,
      includeTitleTags: true,
      headingsOffset  : -boardTop,
    }, CONFIG.toc));
    if (toc.find('.toc-list-item').length > 0) {
      toc.css('visibility', 'visible');
    }

    Fluid.events.registerRefreshCallback(function() {
      if ('tocbot' in window) {
        tocbot.refresh();
        var toc = jQuery('#toc');
        if (toc.length === 0 || !tocbot) {
          return;
        }
        if (toc.find('.toc-list-item').length > 0) {
          toc.css('visibility', 'visible');
        }
      }
    });
  });
</script>


  <script src=https://lib.baomitu.com/clipboard.js/2.0.11/clipboard.min.js></script>

  <script>Fluid.plugins.codeWidget();</script>


  
<script>
  Fluid.utils.createScript('https://lib.baomitu.com/anchor-js/4.3.1/anchor.min.js', function() {
    window.anchors.options = {
      placement: CONFIG.anchorjs.placement,
      visible  : CONFIG.anchorjs.visible
    };
    if (CONFIG.anchorjs.icon) {
      window.anchors.options.icon = CONFIG.anchorjs.icon;
    }
    var el = (CONFIG.anchorjs.element || 'h1,h2,h3,h4,h5,h6').split(',');
    var res = [];
    for (var item of el) {
      res.push('.markdown-body > ' + item.trim());
    }
    if (CONFIG.anchorjs.placement === 'left') {
      window.anchors.options.class = 'anchorjs-link-left';
    }
    window.anchors.add(res.join(', '));

    Fluid.events.registerRefreshCallback(function() {
      if ('anchors' in window) {
        anchors.removeAll();
        var el = (CONFIG.anchorjs.element || 'h1,h2,h3,h4,h5,h6').split(',');
        var res = [];
        for (var item of el) {
          res.push('.markdown-body > ' + item.trim());
        }
        if (CONFIG.anchorjs.placement === 'left') {
          anchors.options.class = 'anchorjs-link-left';
        }
        anchors.add(res.join(', '));
      }
    });
  });
</script>


  
<script>
  Fluid.utils.createScript('https://lib.baomitu.com/fancybox/3.5.7/jquery.fancybox.min.js', function() {
    Fluid.plugins.fancyBox();
  });
</script>


  <script>Fluid.plugins.imageCaption();</script>

  <script  src="/js/local-search.js" ></script>

  <script defer src="https://busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js" ></script>




  
<script src="//cdn.jsdelivr.net/gh/EmoryHuang/BlogBeautify@1.1/DynamicRibbon.min.js"></script>



<!-- 主题的启动项，将它保持在最底部 -->
<!-- the boot of the theme, keep it at the bottom -->
<script  src="/js/boot.js" ></script>


  

  <noscript>
    <div class="noscript-warning">博客在允许 JavaScript 运行的环境下浏览效果更佳</div>
  </noscript>
</body>
</html>
